package com.liy.framework.common.token;

import org.bouncycastle.util.encoders.*;
import java.io.*;

public class Base64Utils
{
    private static final int CACHE_SIZE = 1024;
    
    public static byte[] decode(final String base64) throws Exception {
        return Base64.decode(base64.getBytes());
    }
    
    public static String encode(final byte[] bytes) throws Exception {
        return new String(Base64.encode(bytes));
    }
    
    public static String encodeFile(final String filePath) throws Exception {
        final byte[] bytes = fileToByte(filePath);
        return encode(bytes);
    }
    
    public static void decodeToFile(final String filePath, final String base64) throws Exception {
        final byte[] bytes = decode(base64);
        byteArrayToFile(bytes, filePath);
    }
    
    public static byte[] fileToByte(final String filePath) throws Exception {
        byte[] data = new byte[0];
        final File file = new File(filePath);
        if (file.exists()) {
            final FileInputStream in = new FileInputStream(file);
            final ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
            final byte[] cache = new byte[1024];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
            out.close();
            in.close();
            data = out.toByteArray();
        }
        return data;
    }
    
    public static void byteArrayToFile(final byte[] bytes, final String filePath) throws Exception {
        final InputStream in = new ByteArrayInputStream(bytes);
        final File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        destFile.createNewFile();
        final OutputStream out = new FileOutputStream(destFile);
        final byte[] cache = new byte[1024];
        int nRead = 0;
        while ((nRead = in.read(cache)) != -1) {
            out.write(cache, 0, nRead);
            out.flush();
        }
        out.close();
        in.close();
    }
}
